package cn.bjc.pet.service.impl;

import cn.bjc.basic.exception.BusinessException;
import cn.bjc.basic.service.IBaiduAiAuditService;
import cn.bjc.basic.service.impl.BaseServiceImpl;
import cn.bjc.basic.util.CodeGenerateUtils;
import cn.bjc.basic.util.DistanceUtils;
import cn.bjc.basic.util.PageList;
import cn.bjc.basic.util.Point;
import cn.bjc.order.domain.OrderPetAcquisition;
import cn.bjc.order.mapper.OrderPetAcquisitionMapper;
import cn.bjc.org.domain.Employee;
import cn.bjc.org.domain.Shop;
import cn.bjc.org.mapper.EmployeeMapper;
import cn.bjc.org.mapper.ShopMapper;
import cn.bjc.pet.domain.Pet;
import cn.bjc.pet.domain.SearchMasterMsg;
import cn.bjc.pet.domain.SearchMasterMsgAuditLog;
import cn.bjc.pet.dto.AcceptDto;
import cn.bjc.pet.mapper.PetMapper;
import cn.bjc.pet.mapper.SearchMasterMsgAuditLogMapper;
import cn.bjc.pet.mapper.SearchMasterMsgMapper;
import cn.bjc.pet.query.SearchMasterMsgQuery;
import cn.bjc.pet.service.ISearchMasterMsgService;
import cn.bjc.rocketemq.producer.RocketMQProducer;
import cn.bjc.user.domain.User;
import cn.bjc.user.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class SearchMasterMsgServiceImpl extends BaseServiceImpl<SearchMasterMsg> implements ISearchMasterMsgService {

    @Autowired
    private SearchMasterMsgMapper searchMasterMsgMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private ShopMapper shopMapper;
    
    @Autowired
    private EmployeeMapper employeeMapper;
    
    @Autowired
    private PetMapper petMapper;
    
    @Autowired
    private IBaiduAiAuditService baiduAiAuditService;
    
    @Autowired
    private SearchMasterMsgAuditLogMapper searchMasterMsgAuditLogMapper;
    
    @Autowired
    private OrderPetAcquisitionMapper orderPetAcquisitionMapper;
    
    @Autowired
    private RocketMQProducer rocketMQProducer;
    
    //百度自动审核
    @Override
    public void publish(SearchMasterMsg smm,Long id) {
        
        //1.先添加到数据库,t_searchMasterMsg state:0 待审核
        //user_id shop_id
        //通过logininfo查询userid
        User user = userMapper.loadByLogininfoId(id);
        smm.setUser_id(user.getId());
        
        //shop_id:先计算最近的店铺
        //获取当前店铺的point
        Point point = DistanceUtils.getPoint(smm.getAddress());
        Shop nearestShop = DistanceUtils.getNearestShop(point, shopMapper.loadAll());
        smm.setShop_id(nearestShop.getId());

        searchMasterMsgMapper.save(smm);
                
        //2.审核
        //审核图片
        Boolean textBoolean = baiduAiAuditService.textAudit(smm.getTitle() + smm.getName() + smm.getAddress());

        //审核图片
        //Boolean imageBoolean = baiduAiAuditService.imageAudit(smm.getResources());
    
        if(textBoolean){
            //审核通过
            //1.修改状态
            smm.setState(1);
            smm.setNote("待处理");
            searchMasterMsgMapper.update(smm);
            //2.写入日志
            SearchMasterMsgAuditLog smmal = new SearchMasterMsgAuditLog();
            smmal.setMsg_id(smm.getId());
            smmal.setState(1);
            smmal.setAudit_time(new Date());
            smmal.setNote("待处理状态！");

            // 保存审核日志信息
            searchMasterMsgAuditLogMapper.save(smmal);
            
            //发送短信/邮件
            
        } else {
            //审核不通过
            //1.修改状态
            smm.setNote("驳回");
            searchMasterMsgMapper.update(smm);
            //2.写入日志
            SearchMasterMsgAuditLog smmal = new SearchMasterMsgAuditLog();
            smmal.setMsg_id(smm.getId());
            smmal.setState(0);
            smmal.setAudit_time(new Date());
            smmal.setNote("审核不通过,驳回");

            // 保存审核日志信息
            searchMasterMsgAuditLogMapper.save(smmal);
            throw new BusinessException("信息异常,请重新录入");
        }

    }

    //待审核
    @Override
    public PageList<SearchMasterMsg> toAudit(SearchMasterMsgQuery query, Long id) {
        //通过logininfoid查询employee
        Employee emp = employeeMapper.loadByLogininfoId(id);
        //待处理状态
        query.setState(0);
        if(emp.getShop_id()!=null){
            query.setShopId(emp.getShop_id());
        }
        return super.pageQuery(query);
    }

    /**
     * 待处理
     * @param query
     * @param id
     * @return
     */
    @Override
    public PageList<SearchMasterMsg> toHandle(SearchMasterMsgQuery query, Long id) {
        //通过logininfoid查询employee
        Employee emp = employeeMapper.loadByLogininfoId(id);
        //待处理状态
        query.setState(1);
        if(emp.getShop_id()!=null){
            query.setShopId(emp.getShop_id());
        }
        return super.pageQuery(query);
    }

    @Override
    public PageList<SearchMasterMsg> user(SearchMasterMsgQuery query, Long id) {
        //查询到用户id
        User user = userMapper.loadByLogininfoId(id);
        query.setUserId(user.getId()); 

        return super.pageQuery(query);
    }
    
    //拒单
    @Override
    public void reject(Long id) {
        searchMasterMsgMapper.reject(id);
    }

    //接单
    @Override
    public void accept(AcceptDto dto, Long id) {
        Long empId = dto.getHandler();
        Long msgId = dto.getMsgId();
        String note = dto.getNote();
        //根据smmid查询订单,如果有订单,则该订单正在处理中
        OrderPetAcquisition order = orderPetAcquisitionMapper.loadBySmmId(msgId);
        if (order!=null){
            throw new BusinessException("该订单已经在处理中,请勿重复操作");
        }
        //1.生成一个pet
        SearchMasterMsg searchMasterMsg = searchMasterMsgMapper.loadById(msgId);
        Pet pet = searchMasterMsg2Pet(searchMasterMsg);
        //保存pet
        petMapper.save(pet);

        //2.生成一个收购订单
        OrderPetAcquisition opa = ininOrderPetAcquisition(dto,pet,searchMasterMsg);
        
        //3.保存这个订单
        orderPetAcquisitionMapper.save(opa);
        
        //4.获取到这个订单的id
        OrderPetAcquisition orderMsg = orderPetAcquisitionMapper.loadById(opa.getId());
        //5.sendDelayMsg:发送延迟消息,设置延时消息等级,测试暂定为5
        //放入的消息体的是order的sn编号
        rocketMQProducer.sendDelayMsg(orderMsg.getOrderSn(), 5);

    }

    //生成一个收购订单
    private OrderPetAcquisition ininOrderPetAcquisition(AcceptDto dto, Pet pet, SearchMasterMsg smm) {
        // 创建一个订单对象，赋值
        OrderPetAcquisition order = new OrderPetAcquisition();

        // 随机生成一个订单编号
        order.setOrderSn(CodeGenerateUtils.generateOrderSn(smm.getUser_id()));
        // 摘要
        order.setDigest("【"+smm.getTitle()+"】");
        // 最后确认时间 定时任务
        order.setLastcomfirmtime(new Date(System.currentTimeMillis()+60*1000));//设置5级,此处暂定60秒

        order.setState(0);// 待处理
        order.setPrice(smm.getPrice());
        order.setPet_id(pet.getId());
        order.setUser_id(smm.getUser_id());
        order.setShop_id(smm.getShop_id());
        order.setAddress(smm.getAddress());
        order.setEmp_id(dto.getHandler());
        order.setSearch_master_msg_id(dto.getMsgId());
        return order;
    }

    //通过searchMasterMsg生成Pet
    private Pet searchMasterMsg2Pet(SearchMasterMsg smm) {
        Pet pet = new Pet();

        pet.setName(smm.getName());
        pet.setCostprice(smm.getPrice());
        pet.setType_id(smm.getPetType());
        pet.setResources(smm.getResources());
        pet.setShop_id(smm.getShop_id());
        pet.setSearch_master_msg_id(smm.getId());
        
        return pet;
    }

    //已处理
    @Override
    public PageList<SearchMasterMsg> finish(SearchMasterMsgQuery query, Long id) {
        //通过logininfoid查询employee
        Employee emp = employeeMapper.loadByLogininfoId(id);
        //已处理状态
        query.setState(2);
        if(emp.getShop_id()!=null){
            query.setShopId(emp.getShop_id());
        }
        return super.pageQuery(query);
    }
    
}
